﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AMS.DataAccess.Trademark.Interfaces;
using AMS.DataAccess.Trademark.Filters;
using AMS.DataAccess.Trademark.BO;
using System.Data;
using AMS.DataAccess.Trademark.BO.Enums;

public partial class Task_MyTasks : BaseWorkPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            drpChangeStatus.Attributes["onchange"] = "if(!preCheckItems('gv')){event.cancelBubble=true; return false;}";
            DoDataBind();
        }
    }

    #region DataBind and pager events
    TaskFilter filter;
    private void DoDataBind()
    {
        int total = 0;
        ITaskManager taskMgr = ManagerFactory.CreateTaskManager();
        if (filter == null)
        {
            filter = ucSearchTask1.GetTaskFilter();
            // TODO: enable owner id here
            // filter.OwnerID = CallContext.UserID;
        }

        List<TaskInfo> taskList = taskMgr.GetPagedTaskList(CallContext, filter, pager.CurrentPageIndex, pager.PageSize, out total);
        gv.DataSource = taskList;
        gv.DataKeyNames = new string[] { "AID" };
        gv.DataBind();
        BindPager(total);

        int newTaskCount = 0;
        int unFinishedTaskCount = 0;
        DataTable dtSummary = taskMgr.GetMyTaskSummaryByStatus(CallContext, false);
        foreach (DataRow row in dtSummary.Rows)
        {
            int status = (int)row["Status"];
            if (status == (int)TaskStatus.NewTask)
            {
                newTaskCount += (int)row["StatusCount"];
                unFinishedTaskCount += (int)row["StatusCount"];
            }
            else if (status == (int)TaskStatus.UnCompleted)
            {
                unFinishedTaskCount += (int)row["StatusCount"];
            }
        }

        lblNewTaskCount.Text = newTaskCount.ToString();
        lblTotal.Text = unFinishedTaskCount.ToString();
    }

    void BindPager(int totalCount)
    {
        pager.RecordCount = totalCount;
        pager2.RecordCount = totalCount;
    }

    protected string FormatDateTime(object value, bool includeTime)
    {
        return Utils.FormateDateTime(value, includeTime);
    }

    protected void pager_PageChanged(object sender, EventArgs e)
    {
        DoDataBind();
    }

    protected void pager2_PageChanged(object sender, EventArgs e)
    {
        DoDataBind();
    }
    #endregion


    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        DoDataBind();
    }

    protected void btnMarkFinished_Click(object sender, EventArgs e)
    {
        BatchChangeTaskStatus(TaskStatus.Completed);
    }

    protected void btnCloseTasks_Click(object sender, EventArgs e)
    {
        List<int> selectedIDs = GetCheckItemIDs();
        ITaskManager taskMgr = ManagerFactory.CreateTaskManager();
        int count = taskMgr.BatchChangeTaskStatus(CallContext,
            selectedIDs.ToArray(),
            TaskStatus.Closed,
            new TaskStatus[] { TaskStatus.Checked });

        if (selectedIDs.Count == count)
        {
            MsgInfo(string.Format("关闭{0}项任务。", count));
        }
        else
        {
            MsgWarning(string.Format("成功{0}, 失败{1}。<br/>失败原因：只有处于完成状态下的任务才能被关闭。",
                count,
                selectedIDs.Count - count));
        }

        if (count > 0)
        {
            DoDataBind();
        }
    }

    void BatchChangeTaskStatus(TaskStatus status)
    {
        BatchChangeTaskStatus(status, null);
    }

    void BatchChangeTaskStatus(TaskStatus status, TaskStatus[] prevStatusList)
    {
        List<int> selectedIDs = GetCheckItemIDs();
        ITaskManager taskMgr = ManagerFactory.CreateTaskManager();
        int count = taskMgr.BatchChangeTaskStatus(CallContext,
            selectedIDs.ToArray(),
            status,
            prevStatusList);

        if (selectedIDs.Count == count)
        {
            MsgInfo(string.Format("成功{0}。", count));
        }
        else
        {
            MsgWarning(string.Format("成功{0}, 失败{1}。<br/>失败原因：任务可能已被删除，或与预设的状态不匹配。",
                count,
                selectedIDs.Count - count));
        }

        if (count > 0)
        {
            DoDataBind();
        }
    }

    List<int> GetCheckItemIDs()
    {
        List<int> ids = new List<int>();
        foreach (GridViewRow row in gv.Rows)
        {
            CheckBox chk = row.FindControl("chk") as CheckBox;
            if (chk.Checked)
            {
                int id = Convert.ToInt32(gv.DataKeys[row.RowIndex].Value);
                ids.Add(id);
            }
        }

        return ids;
    }

    protected void searchTask_OnFilterTask(object sender, EventArgs<TaskFilter> args)
    {
        filter = args.CommandArgument;
        // TODO: enable owner id
        //filter.OwnerID = CallContext.UserID;
        DoDataBind();
    }
    protected void drpChangeStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (drpChangeStatus.SelectedIndex > 0)
        {
            switch (drpChangeStatus.SelectedIndex)
            {
                case 1:
                    BatchChangeTaskStatus(TaskStatus.NewTask, new TaskStatus[] { TaskStatus.NewTask, TaskStatus.UnCompleted, TaskStatus.Completed });
                    break;

                case 2:
                    BatchChangeTaskStatus(TaskStatus.UnCompleted);
                    break;

                case 3:
                    BatchChangeTaskStatus(TaskStatus.Completed);
                    break;

                default:
                    throw new NotImplementedException("未实现");
                    break;
            }
        }

        drpChangeStatus.SelectedIndex = 0;
    }
}
